package com.lxmes.gs.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lxmes.common.core.text.Convert;
import com.lxmes.gs.domain.*;
import com.lxmes.gs.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxmes.gs.mapper.MyWorkingHoursMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 我的工时Service业务层处理
 * 
 * @author wdf
 * @date 2023-04-24
 */
@Service
public class MyWorkingHoursServiceImpl extends ServiceImpl<MyWorkingHoursMapper,MyWorkingHours> implements IMyWorkingHoursService{
    
    @Autowired
    private MyWorkingHoursMapper myWorkingHoursMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private IWorkingHoursSubmissionService workingHoursSubmissionService;
    @Autowired
    private ITaskProgressService taskProgressService;
    @Autowired
    private ITaskStatisticsService taskStatisticsService;
    @Autowired
    private IMyTaskService myTaskService;
    @Autowired
    private IWorkingHoursStandardService workingHoursStandardService;
    /**
     * 查询我的工时
     * 
     * @param id 我的工时主键
     * @return 我的工时
     */
    @Override
    public MyWorkingHours selectMyWorkingHoursById(Long id){
        return myWorkingHoursMapper.selectById(id);
    }

    /**
     * 查询我的工时列表
     * 
     * @param myWorkingHours 我的工时
     * @return 我的工时
     */
    @Override
    public List<MyWorkingHours> selectMyWorkingHoursList(MyWorkingHours myWorkingHours){
        return myWorkingHoursMapper.selectList(Wrappers.lambdaQuery(myWorkingHours));
    }

    /**
     * 新增我的工时
     * 
     * @param myWorkingHours 我的工时
     * @return 结果
     */
    @Override
    public int insertMyWorkingHours(MyWorkingHours myWorkingHours){
        return myWorkingHoursMapper.insert(myWorkingHours);
    }

    /**
     * 修改我的工时
     * 
     * @param myWorkingHours 我的工时
     * @return 结果
     */
    @Override
    public int updateMyWorkingHours(MyWorkingHours myWorkingHours){
        return myWorkingHoursMapper.updateById(myWorkingHours);
    }

    /**
     * 批量删除我的工时
     * 
     * @param ids 需要删除的我的工时主键
     * @return 结果
     */
    @Override
    public int deleteMyWorkingHoursByIds(Long[] ids){
        return myWorkingHoursMapper.deleteMyWorkingHoursByIds(ids);
    }

    /**
     * 删除我的工时信息
     * 
     * @param id 我的工时主键
     * @return 结果
     */
    @Override
    public int deleteMyWorkingHoursById(Long id){
        return myWorkingHoursMapper.deleteById(id);
    }
    @Override
    public String imporIteminfo(List<MyWorkingHours> myWorkingHoursList, boolean updateSupport) {
        if (StringUtils.isNull(myWorkingHoursList) || myWorkingHoursList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MyWorkingHours myWorkingHours : myWorkingHoursList)
        {
            try
            {
                BeanValidators.validateWithException(validator, myWorkingHours);
                this.insertMyWorkingHours(myWorkingHours);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditMyWorkingHours(Long[] ids) {
        List<MyWorkingHours> workingHoursList = baseMapper.selectBatchIds(Arrays.asList(ids));
        if (workingHoursList.stream().anyMatch(i -> StrUtil.equals(i.getAudit(), "1"))) {
            throw new ServiceException("存在已审核数据，操作失败");
        }
        workingHoursList.forEach(i ->{
            i.setAudit("1");
            i.setReportTime(new Date());
        });
        this.updateBatchById(workingHoursList);
        for (MyWorkingHours myWorkingHours : workingHoursList) {
            WorkingHoursSubmission workingHoursSubmission = BeanUtil.copyProperties(myWorkingHours, WorkingHoursSubmission.class);
            workingHoursSubmission.setAudit("0");
            workingHoursSubmissionService.insertWorkingHoursSubmission(workingHoursSubmission);
            
            
            TaskProgress taskProgress = new TaskProgress();
            //计算计划工时
            MyTask myTask = myTaskService.getOne(Wrappers.lambdaQuery(MyTask.class).eq(MyTask::getTaskCode, myWorkingHours.getTaskCode()));
            long planTime = DateUtil.between(myTask.getStartTime(), myTask.getEndTime(), DateUnit.MINUTE);
            //计算累计工时
            List<WorkingHoursSubmission> workingHoursSubmissionList = workingHoursSubmissionService.list(Wrappers.lambdaQuery(WorkingHoursSubmission.class).eq(WorkingHoursSubmission::getTaskCode, myWorkingHours.getTaskCode()));
            Double accumulatedWorkingHours = workingHoursSubmissionList.stream().mapToDouble(i->i.getAccumulatedWorkingHours().doubleValue()).sum();
            //得出任务状态   累计工时/计划工时
            taskProgress.setTaskStatus(Convert.toStr(NumberUtil.div(accumulatedWorkingHours, Convert.toDouble(planTime))));
            taskProgressService.insertTaskProgress(taskProgress);


            TaskStatistics taskStatistics = BeanUtil.copyProperties(myWorkingHours, TaskStatistics.class);
            WorkingHoursStandard workingHoursStandard = workingHoursStandardService.getOne(Wrappers.lambdaQuery(WorkingHoursStandard.class).eq(WorkingHoursStandard::getProjectCode, myWorkingHours.getProjectCode()));
            if (ObjectUtil.isNull(workingHoursStandard.getWorkingHoursUnitPrice())) {
                throw new ServiceException("工时标准中的工时单价未空，操作失败");
            }
            taskStatistics.setWorkingHoursUnitPrice(workingHoursStandard.getWorkingHoursUnitPrice());
            taskStatistics.setCurrentCost(taskStatistics.getCurrentWorkingHours() * taskStatistics.getWorkingHoursUnitPrice());
            taskStatistics.setTotalCost(taskStatistics.getAccumulatedWorkingHours() * taskStatistics.getWorkingHoursUnitPrice());
            taskStatistics.setTaskStatus(taskProgress.getTaskStatus());
            taskStatisticsService.insertTaskStatistics(taskStatistics);
        }
        return 1;
    }
}
